package shuashuami.hb.com.avtivity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import shuashuami.hb.com.fragment.CTaskDescriptionFragment;
import shuashuami.hb.com.fragment.EvaluationDescriptionFragment;
import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.glid.GlidUtil;
import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.hdlibrary.util.fragment.ZoomOutPageTransformer;
import shuashuami.hb.com.htmlutil.MyImageGetter;
import shuashuami.hb.com.htmlutil.MyTagHandler;
import shuashuami.hb.com.http.HttpCMethods;
import shuashuami.hb.com.http.HttpOnNextListener;
import shuashuami.hb.com.http.LoginHttp;
import shuashuami.hb.com.share.ShareCUserInfo;
import shuashuami.hb.com.util.CenterAlignImageSpan;
import shuashuami.hb.com.view.PagerSlidingTabStrip;

public class CHallInfoActivity extends AbActivity {

    private ImageView imgHallImage;
    private TextView tvTitle;
    private TextView tvDate, tvGroupBuyingPrice;
    private TextView tvNumber, tvAdvanceFunds, tvTaskCommission;
    private TextView tvCaozuobuzhou;

    private ImageView imgUserHaed;
    private TextView tvName, tvUserId;

    private ViewPager contentPager;
    private mPagerAdapter adapter;
    private PagerSlidingTabStrip tabs;

    private CTaskDescriptionFragment cTaskDescriptionFragment;
    private EvaluationDescriptionFragment evaluationDescriptionFragment;

    private String id;
    private String num;

    private GlidUtil glidUtil;

    private Button btnSubmit;
    private Button btnQianwanggoumai;

    private String goodsUrl;

    @Override
    protected void initUI() {
        setAbContentView(R.layout.activity_chall_info);
        imgHallImage = (ImageView) findViewById(R.id.img_chall_info_image);
        tvTitle = (TextView) findViewById(R.id.tv_chall_info_title);
        tvDate = (TextView) findViewById(R.id.tv_chall_info_date);
        tvGroupBuyingPrice = (TextView) findViewById(R.id.tv_chall_info_group_buying_price);
        tvNumber = (TextView) findViewById(R.id.tv_chall_info_number);
        tvAdvanceFunds = (TextView) findViewById(R.id.tv_chall_info_advance_funds);
        tvTaskCommission = (TextView) findViewById(R.id.tv_chall_info_task_commission);
        tvCaozuobuzhou = (TextView) findViewById(R.id.tv_chall_info_caozuobuzhou);

        imgUserHaed = (ImageView) findViewById(R.id.img_chall_info_user_head_image);
        tvName = (TextView) findViewById(R.id.tv_chall_info_user_name);
        tvUserId = (TextView) findViewById(R.id.tv_chall_info_user_id);

        contentPager = (ViewPager) findViewById(R.id.content_pager_chall_info);
        adapter = new mPagerAdapter(getSupportFragmentManager());
        contentPager.setAdapter(adapter);
        contentPager.setOffscreenPageLimit(2);
        contentPager.setPageTransformer(true, new ZoomOutPageTransformer());

        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs_chall_info);
        tabs.setTextColorResource(R.color.gray);
        tabs.setDividerColorResource(R.color.view_unpressed);
        tabs.setIndicatorColorResource(R.color.blue);
        tabs.setSelectedTextColorResource(R.color.blue);
        tabs.setIndicatorHeight(4);
        tabs.setUnderlineHeight(2);
        tabs.setTextSize(12);
        tabs.setViewPager(contentPager);

        btnSubmit = (Button) findViewById(R.id.btn_chall_info_submit);
        btnQianwanggoumai = (Button) findViewById(R.id.btn_chall_info_qianwanggoumai);
    }

    @Override
    protected void initData() {
        setTitleBar("任务详细");
        setLeftView();
        glidUtil = new GlidUtil(this);
        cTaskDescriptionFragment = new CTaskDescriptionFragment();
        evaluationDescriptionFragment = new EvaluationDescriptionFragment();
        Bundle bundle = this.getIntent().getExtras();/*获取Bundle中的数据，注意类型和key*/
        id = bundle.getString("id");
        num = bundle.getString("num");
        getMessage();
    }

    private String title;

    private void setTvTitle(final String imageURl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Drawable drawable = loadImageFromNetwork(imageURl);
                Message message = handler.obtainMessage(2);     // Message
                message.obj = drawable;
                handler.sendMessageDelayed(message, 0);

            }
        }).start();

    }

    private Drawable loadImageFromNetwork(String urladdr) {
        Drawable drawable = null;
        try {
            drawable = Drawable.createFromStream(new URL(urladdr).openStream(), "image.jpg");
        } catch (IOException e) {
        }

        return drawable;

    }

    @Override
    protected void initListener() {
        btnQianwanggoumai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(goodsUrl.trim());
                intent.setData(content_url);
                startActivity(intent);
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
                intent = new Intent(CHallInfoActivity.this, CUntreatedTaskInfoActivity.class);

                Bundle bundle = new Bundle();
        /*字符、字符串、布尔、字节数组、浮点数等等，都可以传*/
                bundle.putString("id", id);
                bundle.putString("num", num);

		/*把bundle对象assign给Intent*/
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
            }
        });
    }

    private class mPagerAdapter extends FragmentStatePagerAdapter {

        private String Title[] = {"任务说明", "评价说明"};

        public mPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            if (arg0 == 0) {
                return cTaskDescriptionFragment;
            } else {
                return evaluationDescriptionFragment;
            }

        }

        @Override
        public int getCount() {
            return Title.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return Title[position];
        }

    }

    private void getMessage() {
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(1);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);

            }
        };
        ShareCUserInfo shareCUserInfo = new ShareCUserInfo(this);
        HttpCMethods.getHallInfo(listener, shareCUserInfo.getId(), id);
    }

    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 203) {
                            LoginHttp loginHttp = new LoginHttp(CHallInfoActivity.this);
                            loginHttp.login();
                            return;
                        }
                        if (jsonObject.getInt("status") == 200) {
                            JSONObject temp = jsonObject.getJSONObject("content");
                            tvDate.setText(temp.getString("addtime"));
                            tvGroupBuyingPrice.setText("$" + temp.getString("price"));
                            tvNumber.setText(temp.getString("num") + "件");
                            tvAdvanceFunds.setText(temp.getString("spot_money") + "元");
                            tvTaskCommission.setText(temp.getString("commission") + "元");
                            setCaozuo(temp.getString("operate"));
                            setTvTitle(temp.getString("platform_image"));
                            title = temp.getString("goods_title");
                            goodsUrl = temp.getString("goods_url");
                            glidUtil.uploadImage(temp.getString("goods_image"), R.mipmap.ic_launcher, imgHallImage);
                            JSONObject shop = temp.getJSONObject("shop");
                            tvName.setText(shop.getString("username"));
                            tvUserId.setText("商家 ID: " + shop.getString("id"));
                            glidUtil.uploadCircle(shop.getString("avatar"), imgUserHaed, R.mipmap.ssm_icon_11);
                            cTaskDescriptionFragment.setMessage(temp.getString("task_sn"), temp.getString("platform_name"), temp.getString("goods_type_name"),
                                    temp.getString("type_name"), temp.getString("need_comment_text"));
                            String str = temp.getString("goods_type_name");
                            if (str.equals("扫码任务")) {
                                btnQianwanggoumai.setVisibility(View.VISIBLE);
                            } else {
                                btnQianwanggoumai.setVisibility(View.GONE);
                            }

                            if (temp.has("comment")) {
                                List<String> images = new ArrayList<>();
                                if (!temp.getString("comment_images").equals("")) {
                                    JSONArray jsonImages = temp.getJSONArray("comment_images");
                                    for (int i = 0; i < jsonImages.length(); i++) {
                                        images.add(jsonImages.getString(i));
                                    }
                                }
                                evaluationDescriptionFragment.setMessage(temp.getString("comment"), images);
                            }

                        } else {
                            ToastUtil.showShort(CHallInfoActivity.this, jsonObject.getString("message"));
                        }

                    } catch (JSONException e) {
                        ToastUtil.showShort(CHallInfoActivity.this, "数据解析错误");
                    }


                    break;
                case 2:
                    Drawable drawable = (Drawable) msg.obj;
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(title + "（图片）");
                    SpannableString spannableStringImg = new SpannableString(buffer);
                    //         Drawable drawable = getResources().getDrawable(R.mipmap.home_icon_jingdong);
                    drawable.setBounds(0, 0, 40, 40);
                    CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable);
                    spannableStringImg.setSpan(imageSpan, buffer.length() - 4, buffer.length(), ImageSpan.ALIGN_BASELINE);
                    tvTitle.setText(spannableStringImg);
                    break;
            }

            super.handleMessage(msg);
        }
    };

    private void setCaozuo(String str) {//网页

        Spanned spanned = Html.fromHtml(str, new MyImageGetter(this, tvCaozuobuzhou), new MyTagHandler(this));
        tvCaozuobuzhou.setText(spanned);
        tvCaozuobuzhou.setMovementMethod(LinkMovementMethod.getInstance());
    }


}
